﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bzure.Common.Data;
using Bzure.Security.Permissions;

namespace Bzure.Apps.Security.DataAccess
{
    public class DroitResourceRepository : RepositoryBase
    {
        static DroitResourceRepository()
        {
            DroitResource entity = new DroitResource(Guid.NewGuid().ToString());
            Type type = entity.GetType();
            AppendDataMap(type, "ResourceID", () => entity.ResourceID);
            AppendDataMap(type, "ResourceName", () => entity.ResourceName);
            AppendDataMap(type, "RoleID", () => entity.RoleID);
            AppendDataMap(type, "RightValue", () => entity.RightValue);
            AppendDataMap(type, "State", () => entity.State);
            ResultMapDelegate<DroitResource> queryMap = Resource_Map;
            QueryMapContainer[entity.GetType()] = queryMap;
        }
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="contractProvider"></param>
        public DroitResourceRepository(Bzure.Common.Transactions.ITransactionSupport contractProvider)
            : base(contractProvider)
        {

        }
        /// <summary>
        /// 实体对应数据库中的表
        /// </summary>
        public override string TableName
        {
            get
            {
                return "T_Security_DroitResources";
            }
        }
        /// <summary>
        /// 角色实体数据映射
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static DroitResource Resource_Map(DataReader reader)
        {
            DroitResource resource = new DroitResource(reader.GetString("ResourceID"))
            {
                ResourceName = reader.GetString("ResourceName"),
                RoleID = reader.GetString("RoleID"),
                RightValue = reader.GetInt("RightValue"),
                State = reader.GetInt("State")
            };
            return resource;
        }
        public DroitResource[] GetDroitsByRole(ISecurityRole role)
        {
            string sql = string.Format("SELECT * FROM  {0} WHERE RoleID=@RoleID", this.TableName);
            return new SqlEntityMap<DroitResource>(this.ContractProvider, sql)
                .AddString("RoleID", role.ID)
                .SetMap(Resource_Map)
                .AsList().ToArray();
        }
    }
}
